package com.csdj.middleware.config;

import com.csdj.middleware.MqttMsgHandler;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.handler.annotation.Header;

import java.util.Objects;

@Configuration
@ConditionalOnProperty(prefix = "mqtt",name = "switch",havingValue = "on")
public class MqttConfig {

    //发送消息通道名
    public static final String OUTBOUND_CHANNEL = "mqttOutboundChannel";

    //接受消息通道名
    public static final String INPUT_CHANNEL = "mqttInputChannel";
    //topic在消息头中的key
    public static final String TOPIC_IN_HEADERS = "mqtt_receivedTopic";

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.url}")
    private String hostUrl;

    @Value("${mqtt.clientId}")
    private String clientId;

    @Value("${mqtt.defaultTopic}")
    private String defaultTopic;


    /**
     * mqtt服务器信息配置
     * @return
     */
    public MqttConnectOptions getMqttConnectOptions(){
        MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        return mqttConnectOptions;
    }

    /**
     * 创建客户端工厂类
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }


    /**
     * 输入消息通道
     * @return
     */
    @Bean(name = INPUT_CHANNEL)
    public MessageChannel mqttInputChannel(){
        return new DirectChannel();
    }
    /**
     * 消息订阅
     * 配置client,监听的topic
     */
    @Bean
    public MessageProducer inbound(MqttPahoClientFactory factory,MessageChannel mqttInputChannel) {
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(clientId, factory, defaultTopic);
        adapter.setCompletionTimeout(3000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel);
        return adapter;
    }

    /**
     * 必须实现MqttMsgHandler接口并交给spring管理
     * 消息消费
     * 消息头
     * headers={
     * mqtt_receivedRetained=false,
     * mqtt_id=0,
     * mqtt_duplicate=false,
     * id=5da3fed6-1b1b-f60e-ca04-795a7c9a6ebc,
     * mqtt_receivedTopic=root/lot,
     * mqtt_receivedQos=0,
     * timestamp=1625909355437}
     * @return
     */
    @Bean
    @ConditionalOnBean(MqttMsgHandler.class)
    @ServiceActivator(inputChannel = INPUT_CHANNEL)
    public MessageHandler handler(MqttMsgHandler handler) {
        return message -> {
            String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
            String msg  = message.getPayload().toString();
            handler.onMessage(topic,msg);
        };
    }


    @Bean(name = OUTBOUND_CHANNEL)
    public MessageChannel outbound(){
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = OUTBOUND_CHANNEL)
    public MqttPahoMessageHandler mqttPahoMessageHandler(){
        MqttPahoMessageHandler messageHandler =
                new MqttPahoMessageHandler(clientId, mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(defaultTopic);
        return messageHandler;
    }

    @MessagingGateway(defaultRequestChannel = OUTBOUND_CHANNEL)
    public interface MyGateway {
        void sendToMqtt(String data);
        void sendToMqtt(String data,@Header(MqttHeaders.TOPIC) String topic);
    }


}
